package com.zxl.yunpicture.interfaces.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zxl.yunpicture.application.service.PictureApplicationService;
import com.zxl.yunpicture.application.service.UserApplicationService;
import com.zxl.yunpicture.domain.picture.entity.Picture;
import com.zxl.yunpicture.domain.user.constant.UserConstant;
import com.zxl.yunpicture.domain.user.entity.User;
import com.zxl.yunpicture.infrastructure.annotation.AuthCheck;
import com.zxl.yunpicture.infrastructure.common.BaseResponse;
import com.zxl.yunpicture.infrastructure.common.DeleteRequest;
import com.zxl.yunpicture.infrastructure.common.ResultUtils;
import com.zxl.yunpicture.infrastructure.exception.BusinessException;
import com.zxl.yunpicture.infrastructure.exception.ErrorCode;
import com.zxl.yunpicture.infrastructure.exception.ThrowUtils;
import com.zxl.yunpicture.interfaces.assembler.UserAssembler;
import com.zxl.yunpicture.interfaces.dto.user.*;
import com.zxl.yunpicture.interfaces.vo.user.LoginUserVO;
import com.zxl.yunpicture.interfaces.vo.user.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {


    @Resource
    private UserApplicationService userApplicationService;


    @Resource
    private PictureApplicationService pictureApplicationService;


    /**
     * 用户注册
     * @return
     */
    @PostMapping("/register")
    //@AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest){
        ThrowUtils.throwIf(userRegisterRequest == null, ErrorCode.PARAMS_ERROR);
        long result = userApplicationService.userRegister(userRegisterRequest);
        return ResultUtils.success(result);
    }

    /**
     * 用户登录
     * @param userLoginRequest
     * @param request
     * @return
     */
    @PostMapping("/login")
    public BaseResponse<LoginUserVO> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request){
        ThrowUtils.throwIf(userLoginRequest == null,ErrorCode.PARAMS_ERROR);
        LoginUserVO loginUserVO = userApplicationService.userLogin(userLoginRequest,request);
        return ResultUtils.success(loginUserVO);
    }

    /**
     * 获取当前登录用户
     * @param request
     * @return
     */
    @GetMapping("/get/login")
    public BaseResponse<LoginUserVO> getLoginUser(HttpServletRequest request){
        User loginUser = userApplicationService.getLoginUser(request);
        return ResultUtils.success(userApplicationService.getLoginUserVO(loginUser));
    }

    /**
     * 退出登录
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public BaseResponse<Boolean> userLogout(HttpServletRequest request){
        boolean flag = userApplicationService.userLogout(request);
        return ResultUtils.success(flag);
    }


    /**
     * 创建用户
     * @param userAddRequest
     * @return
     */
    @PostMapping("/userAdd")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> userAdd(@RequestBody UserAddRequest userAddRequest){
        ThrowUtils.throwIf(userAddRequest == null,ErrorCode.PARAMS_ERROR);
        User userEntity = UserAssembler.toUserEntity(userAddRequest);
        userApplicationService.saveUser(userEntity);
        return ResultUtils.success(userEntity.getId());
    }


    /**
     * 根据id获取用户（仅限管理员）
     * @param id
     * @return
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<User> getUserById(long id){
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        User user = userApplicationService.getUserById(id);
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(user);
    }


    /**
     * 根据id获取包装类
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<UserVO> getUserVOById(long id){
        BaseResponse<User> response = getUserById(id);
        User user = response.getData();
        return ResultUtils.success(userApplicationService.getUserVO(user));
    }

    /**
     * 根据id删除用户
     * @param deleteRequest
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest,HttpServletRequest request){
        if (deleteRequest == null || deleteRequest.getId() <= 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //根据删除的用户id查询到其管理的图片列表，将图片删除
        LambdaQueryWrapper<Picture> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Picture::getUserId, deleteRequest.getId());
        List<Picture> pictureList = pictureApplicationService.list(wrapper);
        for (Picture oldPicture : pictureList){
            pictureApplicationService.clearPictureFile(oldPicture);
            DeleteRequest deletePicture = new DeleteRequest();
            deletePicture.setId(oldPicture.getId());
            User loginUser = userApplicationService.getLoginUser(request);
            pictureApplicationService.deletePicture(deletePicture.getId(),loginUser);
        }
        boolean b = userApplicationService.deleteUser(deleteRequest);
        return ResultUtils.success(b);
    }


    /**
     * 更新用户
     * @param userUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateUser(@RequestBody UserUpdateRequest userUpdateRequest){
        if (userUpdateRequest == null || userUpdateRequest.getId() == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //对象转换
        User userEntity = UserAssembler.toUserEntity(userUpdateRequest);
        userApplicationService.updateUser(userEntity);
        return ResultUtils.success(true);

    }

    /**
     * 分页查询接口
     * @param userQueryRequest
     * @return
     */
    @PostMapping("/list/page/vo")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<UserVO>> listUserVOByPage(@RequestBody UserQueryRequest userQueryRequest){
        ThrowUtils.throwIf(userQueryRequest == null, ErrorCode.PARAMS_ERROR);
        return ResultUtils.success(userApplicationService.listUserVOByPage(userQueryRequest));
    }
}
